<template>
  <el-form ref="menuRuleFormRef" :model="menuRuleForm" label-width="auto" :inline="true">
    <el-form-item label="菜单名称" prop="menuName">
      <el-input v-model.trim="menuRuleForm.menuName" placeholder="请输入菜单名称" />
    </el-form-item>
    <el-form-item label="菜单状态" prop="menuState">
      <el-select v-model="menuRuleForm.menuState" placeholder="请输入菜单状态">
        <el-option :label=item.label :value=item.value v-for="item in options" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(menuRuleFormRef)">
        查询
      </el-button>
      <el-button @click="resetForm(menuRuleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" @click="handleACreate">创建</el-button>
  </div>
  <div>
    <el-table :data="tableData" style="width: 100%" row-key="_id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column :label="item.label" :prop="item.property" v-for="(item, t) in columns" :key="t"
        :formatter="item.formatter" />
      {{ tableData }}
      <el-table-column align="center" label="操作" width="200px">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleAdd(scope.row)" v-has="'user-edit'">新增</el-button>
          <el-button size="small" @click="handleEdit(scope.row)" v-has="'user-edit'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-has="'user-delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="dialogVisible" :title=dynamicTitle width="35%" draggable @close="closeDialog">
    <div>
      <el-form ref="DialogRuleFormRef" style="max-width: 600px" :model="DialogRuleForm" :rules="rules"
        label-width="auto">
        <el-form-item label="父级菜单" prop="paerntId">
          <el-cascader :options="options2" :props="props" v-model="DialogRuleForm.parentId" clearable />
          <span>不些则为一级菜单</span>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="DialogRuleForm.menuType">
            <el-radio :value="1">菜单</el-radio>
            <el-radio :value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="DialogRuleForm.menuName" placeholder="请输入您的菜单名称" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon" v-if="DialogRuleForm.menuType == 1">
          <el-input v-model="DialogRuleForm.icon" placeholder="请输入您的菜单图标" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path" v-if="DialogRuleForm.menuType == 1">
          <el-input v-model="DialogRuleForm.path" placeholder="请输入您的路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="DialogRuleForm.menuType == 1">
          <el-input v-model="DialogRuleForm.component" placeholder="请输入您的组件路径" />
        </el-form-item>
        <el-form-item label="权限标识" prop="menuCode" v-if="DialogRuleForm.menuType == 2">
          <el-input v-model="DialogRuleForm.menuCode" placeholder="请输入您的权限标识" />
        </el-form-item>
        <el-form-item label="状态" prop="menuState">
          <el-radio-group v-model="DialogRuleForm.menuState">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="operateForm(DialogRuleFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, computed } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import Api from './../api/index';
import { ElMessage, ElMessageBox } from 'element-plus'

// 表单数据
const options = [
  { value: 1, label: '停用' },
  { value: 2, label: '在用' },
]
//form
const menuRuleFormRef = ref<FormInstance>()
const menuRuleForm = reactive<RuleForm>({
  menuName: '',
  menuState: 1,
})
//查询
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((vaild)=>{
    if(vaild)
    getMenuList()
  })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// user操作按钮
const dialogVisible = ref(false)
const active = ref('create')
//创建
const handleACreate = () => {
  dialogVisible.value = true
  active.value = 'create'
  // 重置表单
  Object.assign(DialogRuleForm, initialDialogForm);
}

//新增
const handleAdd = (row: any) => {
  dialogVisible.value = true;
  active.value = 'add';
  
  // 重置表单并设置父级ID
  Object.assign(DialogRuleForm, initialDialogForm);
  DialogRuleForm.parentId = row._id;
};

//计算动态标题
const dynamicTitle = computed(() => {
  if (active.value == 'create') {
    return '创建菜单'
  } else if (active.value == 'edit') {
    return '编辑菜单'
  } else if (active.value == 'add') {
    return '新增菜单'
  } else {
    return ''
  }
})


//编辑
const handleEdit = (row: User) => {
  console.log(row)
  active.value = 'edit'
  // 这里需要用异步处理一下，避免bug
  nextTick(() => {
    // 把数据整合，使点击编辑可以拿到该数据
    Object.assign(DialogRuleForm, row)
  })
  dialogVisible.value = true
}
//单个删除处理
const handleDelete = (row: any) => {
  console.log(row)
  ElMessageBox.confirm(
    '你确定要删除这个数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getMenuDeleteListAPI({_id:row._id}).then((res) => {
        if (res) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      })
      getMenuList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//关闭表单重置表单信息
const closeDialog = () => {
  if (DialogRuleFormRef.value) {
    DialogRuleFormRef.value.resetFields();
  }
  // 关键：完全重置表单数据
  Object.assign(DialogRuleForm, initialDialogForm);
};
const tableData = ref<User[]>([])

const columns = [
  {
    label: '菜单名称',
    property: 'menuName'
  },
  {
    label: '图标',
    property: 'icon'
  },
  {
    label: '菜单类型',
    property: 'menuType',
    formatter: function (_row: any, _columns: any, cellValue: string | number, _index: any) {
      const obj: interTable = {
        1: '菜单',
        2: '按钮'
      }
      return obj[cellValue]
    }
  },
  {
    label: '权限标识',
    property: 'menuCode',
  },
  {
    label: '路由地址',
    property: 'path',
  },
  {
    label: '组件路径',
    property: 'component',
  },
  {
    label: '菜单状态',
    property: 'menuState',
    formatter: function (_row: any, _columns: any, cellValue: string | number, _index: any) {
      const obj: interTable = {
        1: '正常',
        2: '停用'
      }
      return obj[cellValue]
    }
  },
  {
    label: '注册时间',
    property: 'createTime'
  }
]

// 定义表单数据类型
const DialogRuleFormRef = ref<FormInstance>()
// 1. 定义初始表单数据常量
const initialDialogForm: DialogMenuRuleForm = {
  menuType: 1,
  menuName: '',
  icon: '',
  path: '',
  menuState: 1,
  component: '',
  parentId: null,
  menuCode: '',
  _id: '' // 确保有这个字段用于重置
};

// 2. 修改表单数据声明
const DialogRuleForm = reactive<DialogMenuRuleForm>({ ...initialDialogForm });
//表单的新增或编辑，连接后端
const operateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate()
  let params: any = DialogRuleForm
  params.active = active.value
    if (active.value === 'create' || active.value === 'add') {
    delete params._id;
  }
  Api.getMenuOperateListAPI(params).then(res => {
    if (res) {
      dialogVisible.value = false
      ElMessage({
        type: 'success',
        message: '设置成功',
      })
      getMenuList()
    }
    
  })

};
//表单验证规则
const rules = reactive<FormRules<DialogMenuRuleForm>>({
  menuName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度为2-10之间', trigger: 'blur' },
  ],

})

//菜单联级选择
const props = {
  checkStrictly: true,
  label: 'menuName',
  value: '_id'
}
const options2 = ref([])
//请求

const getMenuList = () => {
  Api.getMenuListAPI(menuRuleForm).then((res: any) => {
    console.log(res);
    tableData.value = res
    options2.value = res
  })
}



onMounted(() => {
  getMenuList()
})
</script>

<style>
.el-select__input-wrapper.is-hidden {
  position: initial;
}
</style>
